<template>
  <div class="common-layout">
    <el-form class="header" :model="queryParam" ref="queryRef" :inline="true">

      <el-form-item label="书名" prop="ipaddr">
        <el-select style="width: 100px" clearable v-model="queryParam.book" placeholder="书名">
          <el-option v-for="item in 7" :key="item" :label="`${('book')}${item}`" :value="`${('book')}${item}`"/>
        </el-select>
      </el-form-item>

      <el-form-item label="单元名称" prop="ipaddr">
        <el-select style="width: 100px" clearable v-model="queryParam.unit" placeholder="单元名称">
          <el-option v-for="item in 6" :key="item" :label="`${('unit')}${item}`" :value="`${('unit')}${item}`"/>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="searchByUnit">确认</el-button>
        <el-button
            type="danger"
            plain
            :disabled="multiple"
            @click="hiddenEng"
        >{{ multipleEng ? '隐藏英文' : '显示英文' }}
        </el-button>
        <el-button
            type="warning"
            plain
            :disabled="multiple"
            @click="hiddenChn"
        >{{ multipleChn ? '隐藏中文' : '显示中文' }}
        </el-button>

        <el-statistic style="margin-left: 20px;margin-right: 20px" :value="pageData.length">
          <template #title>
            <div style="display: inline-flex; align-items: center">
              当前 / 总数
            </div>
          </template>
          <template #suffix>/ {{ total }}</template>
        </el-statistic>

        <el-button
            :loading="loading"
            type="success"
            @click="submitRecordStudy"
        >
          完成学习
        </el-button>

        <div class="time-display">
          {{ formattedTime }}
        </div>

        <el-button
            plain
            type="primary"
            :disabled="isRunning || (isCountdown && initialTime === 0 && currentTime === 0)"
            @click="startTimer"
        >
          {{ isCountdown && currentTime === 0 && initialTime > 0 && !isRunning ? '开始倒计时' : (isRunning ? '运行中' : '启动') }}
        </el-button>

        <el-button
            plain
            type="warning"
            :disabled="!isRunning"
            @click="pauseTimer"
        >
          暂停
        </el-button>

        <el-button
            plain
            :disabled="isRunning"
            @click="resetTimer"
        >
          重置
        </el-button>

        <el-button type="success" v-if="false" @click="submitRecord">提交记录</el-button>
      </el-form-item>
    </el-form>


    <el-row :gutter="20">
      <el-col :sm="24" :lg="24" style="padding-left: 20px">
        <el-table
            v-loading="loading"
            :data="pageData"
            row-key="_id"
            :expand-row-keys="expandRowKeys"
            @expand-change="handleExpandChange"
            :default-sort="{ prop: 'seed', order: 'descending' }"
            @selection-change="handleSelectionChange"
            border
            stripe
            highlight-current-row
        >
          <el-table-column type="selection" width="40" align="center"/>
          <el-table-column v-if="false" type="index" :index="indexMethod"/>
          <el-table-column label="单词标识" width="100" align="center" prop="seed">
            <template #default="scope">
              <span>{{ scope.row.seed.toString().substring(2, 10) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="编号" v-if="false" width="210" prop="_id"/>
          <el-table-column label="书名" width="80" align="center" prop="book"/>
          <el-table-column label="课程" width="80" align="center" prop="unit"/>
          <el-table-column label="单词/词组" align="center" prop="name"/>
          <el-table-column label="中文名" align="center" prop="chinese"/>
          <el-table-column label="词性" width="80" align="center" prop="type"/>
          <el-table-column label="排序" v-if="false" align="center" prop="number"/>
          <el-table-column label="操作" align="center" width="350" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-button link @click="handleColumnAudio(scope.row)" type="success">发音</el-button>
              <el-button link @click="rowClick(scope.row)" type="primary">已学</el-button>
              <el-button link type="danger" @click="hiddenColumn1(scope.row)">
                {{ scope.row.statusEng ? '显示英文' : '隐藏英文' }}
              </el-button>
              <el-button link type="warning" @click="hiddenColumn2(scope.row)">
                {{ scope.row.statusChn ? '显示中文' : '隐藏中文' }}
              </el-button>
              <el-button link @click="getNetworkInfo(scope.row)" style="color: #421f7d">具体释义</el-button>
            </template>
          </el-table-column>
          <!-- 展开图标列 -->
          <el-table-column type="expand">
            <template #default="props">
              <div v-if="props.row.loadMore" v-html="props.row.loadMoreHtml" class="wordSentence"></div>
              <div style="float: right;color: red;margin-right: 20px" v-else>
                点击‘具体释义’后加载例句
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
      <el-col :sm="24" :lg="8" style="padding-left: 50px">
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
// 查询
import {
  getPageUnit,
  putStudyData,
  putStudyList,
  handleColumnAudio,
  getWordInfoMore,
  getWordSentence,
  getMessageBoxContent
} from "@/api/word/index.js";
import {addStudy_record} from "@/api/word/wordRecord.js";
import {ref} from "vue";
import { useTimerStore } from '@/store/timer';
import '@/assets/styles/word-common.css'
import {ElMessageBox} from "element-plus";

const timerStore = useTimerStore();
// 从 store 中解构 actions
const { startTimer, pauseTimer, resetTimer, toggleMode, setInitialTime } = timerStore;
// 从 store 中解构 state 和 getters (保持响应性)
const { formattedTime, isRunning, isCountdown, initialTime, currentTime } = storeToRefs(timerStore); // 添加 currentTime

let recordFrom = ref({})
let testStartTime = ref(null)
let testEndTime = ref(null)
let testStartTimeStatus = ref(true)

let queryParam = ref({
  unit: '',
  book: ''
})

const {proxy} = getCurrentInstance()

let pageData = ref([])
let correctNum = ref(0)
let studyRecord = ref([])
let selectedData = ref([])
let selectedDataTemp = ref([])
let practiceId = ref(null)
let total = ref(0)
let rowRecordMap = ref(new Map)
let loading = false
let multiple = ref(true)
let multipleEng = ref(true)
let multipleChn = ref(true)

// 允许多个 key
const expandRowKeys = ref([])

// 正确处理：添加或移除 key，而不是覆盖
const handleExpandChange = (row, expandedRows) => {
  // expandedRows 是当前所有展开的行数组
  // console.log('当前展开的行：', expandedRows.map(r => r._id))
  // 如果你想同步 expandRowKeys，可以这样：
  expandRowKeys.value = expandedRows.map(r => r._id)
}

initPage()

//已学，移除本行
function rowClick(row) {
  let number = pageData.value.indexOf(row);
  pageData.value.splice(number, 1);
  proxy.$modal.msgWarning("学会了")
  let temp = row
  delete temp['_id']
  delete temp['seed']
  // temp['time'] = parseTime(new Date())
  temp['practiceId'] = practiceId.value
  putRecord(temp)

  //学习个数
  correctNum.value ++

  //记录首次点击的时间
  if (testStartTimeStatus.value) {
    testStartTime.value = Date.now()
    startTimer()
    testStartTimeStatus.value = false
  }

  studyRecord.value.push(temp)
}

//提交记录-全部-交互
function submitRecord() {
  // console.log(studyRecord)
  if (studyRecord.value.length <= 0) {
    proxy.$modal.msgWarning("未有学习记录")
    return
  }
  proxy.$modal.confirm('学习了' + studyRecord.value.length + '条记录,确认提交？').then(function () {
    putStudyList(studyRecord.value).then(response => {
      // console.log(response)
      if (response.code === 200) {
        studyRecord.value = null
        proxy.$modal.msgSuccess("提交成功")
      }
    })
  }).catch(function () {
    proxy.$modal.msg("取消提交")
  })
}

//提交记录-单个-静默
function putRecord(data) {
  putStudyData(data).then(() => {})
}

function getNetworkInfo(row) {
  let word = row.name
  if (word === null || word === undefined) {
    return
  }
  if (word.toString().indexOf(" ") > -1 || word.toString().indexOf("/") > -1) {
    proxy.$modal.msgWarning("不支持短语查询")
    return
  }
  row.loadMore = true
  getWordInfoMore(word).then(res => {
    if (res.code === 200) {
      // console.log(res.data)
      let wordInfoMore = getMessageBoxContent(res.data);
      row.loadMoreHtml = getWordSentence(res.data.sentences);
      ElMessageBox.alert(wordInfoMore, word, {
        confirmButtonText: 'OK',
        dangerouslyUseHTMLString: true,
        customStyle: {
          'width' : '1200px',
        },
      })
    } else {
      proxy.$modal.msgWarning("请求失败")
    }
  });
}

function handleQuery() {
  loading = true
  getPageUnit(queryParam.value).then((res) => {
    let index = 0
    if (res.code === 200) {
      pageData.value = res.data
      total.value = res.data.length
      pageData.value.forEach(item => {
        item.seed = Math.random()
        item.loadMore = false
        item.loadMoreHtml = ''
        item.statusEng = false
        item.statusChn = false
        item.index = index++
      })
    }
  })
  loading = false
  correctNum.value = 0
  rowRecordMap.value.clear()
}

function initPage() {
  queryParam.value.unit = 'unit' + Math.ceil(Math.random() * 5)
  queryParam.value.book = 'book' + Math.ceil(Math.random() * 6)
  handleQuery()
  practiceId.value = Math.random().toString().substring(2)
  // queryParam.value.unit = undefined
}

function submitRecordStudy() {
  if (correctNum.value === 0){
    proxy.$modal.msgWarning("学习的记录为空")
    return
  }
  if (pageData.value.length > 0) {
    proxy.$modal.msgWarning("还有未学习的单词")
  }

  proxy.$modal.confirm('是否确认提交').then(function () {
    testEndTime.value = Date.now()
    pauseTimer() //完成学习时，停止计时器

    recordFrom.value.book = queryParam.value.book
    recordFrom.value.unit = queryParam.value.unit
    recordFrom.value.wordNum = total.value
    recordFrom.value.practice = practiceId.value
    let usedTime = (testEndTime.value - testStartTime.value) / 1000;
    let timeString
    if (usedTime <= 60) {
      timeString = Math.floor(usedTime) + '秒'
    } else {
      timeString = formatSecondsToChinese(usedTime)
    }
    recordFrom.value.usedTime = timeString
    recordFrom.value.correctNum = correctNum.value
    recordFrom.value.correctRate = correctNum.value / total.value
    // console.log(recordFrom.value)
    handleInsertRecordData(recordFrom.value)
  }).catch(() => {
    proxy.$modal.msg("取消提交")
  })
}

//连接MYSQL数据库-插入数据
function handleInsertRecordData(data) {
  data.type = 'middle'
  addStudy_record(data).then(res => {
    // console.log(res)
    recordFrom.value = {}
    if (res.code === 200) {
      correctNum.value = 0
      practiceId.value = Math.random().toString().substring(2)
      proxy.$modal.msgSuccess("提交成功")
    }
  })
}

function searchByUnit() {
  if (queryParam.value.unit === undefined) {
    return
  }
  resetTimer()
  proxy.$modal.msg("查询的书名:" + queryParam.value.book + "  课程名称:" + queryParam.value.unit)
  handleQuery()
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  selectedData.value = []
  multiple.value = !selection.length
  selection.map(item => {
    selectedData.value.push(item)
  })
  selectedDataTemp.value = JSON.parse(JSON.stringify(selectedData.value))
}

function hiddenEng() {
  if (multipleEng.value) {
    selectedDataTemp.value.forEach(item => {
      let find = pageData.value.find(index => index._id === item._id);
      let number = pageData.value.indexOf(find);
      rowRecordMap.value.set(item.index, item);
      pageData.value[number].name = ''
      pageData.value[number].statusEng = true
    })
  } else {
    selectedDataTemp.value.forEach(item => {
      let find = pageData.value.find(index =>
          index._id === item._id
      );
      let number = pageData.value.indexOf(find);
      pageData.value[number].name = item.name
      pageData.value[number].statusEng = false
    })
  }
  multipleEng.value = !multipleEng.value
}

function hiddenChn() {
  if (multipleChn.value) {
    selectedDataTemp.value.forEach(item => {
      let find = pageData.value.find(index => index._id === item._id);
      let number = pageData.value.indexOf(find);
      rowRecordMap.value.set(item.index, item);
      pageData.value[number].chinese = ''
      pageData.value[number].statusChn = true
    })
  } else {
    selectedDataTemp.value.forEach(item => {
      let find = pageData.value.find(index =>
          index._id === item._id
      );
      let number = pageData.value.indexOf(find);
      pageData.value[number].chinese = item.chinese
      pageData.value[number].statusChn = false
    })
  }
  multipleChn.value = !multipleChn.value
}

const indexMethod = (index) => {
  return index
}

function hiddenColumn1(row) {
  // rowRecord.value = Object.assign({}, row);
  // rowRecord.value = deepClone(row)
  row.statusEng = !row.statusEng
  if (row.statusEng) {
    // rowRecord.value = JSON.parse(JSON.stringify(row))   //对象深拷贝-待用
    if (!rowRecordMap.value.has(row.index)) {
      rowRecordMap.value.set(row.index, JSON.parse(JSON.stringify(row)))
    }
    row.name = ''
  } else {
    row.name = rowRecordMap.value.get(row.index)['name']
  }
}

function hiddenColumn2(row) {
  row.statusChn = !row.statusChn
  if (row.statusChn) {
    if (!rowRecordMap.value.has(row.index)) {
      rowRecordMap.value.set(row.index, JSON.parse(JSON.stringify(row)))
    }
    row.chinese = ''
  } else {
    row.chinese = rowRecordMap.value.get(row.index)['chinese']
  }
}

function deepClone(target) {
  let result;
  if (typeof target === 'object') {
    if (Array.isArray(target)) {
      result = [];
      for (let i in target) {
        result.push(deepClone(target[i]));
      }
    } else if (target === null) {
      result = null;
    } else if (target.constructor === RegExp) {
      result = target;
    } else {
      result = {};
      for (let i in target) {
        if (target.hasOwnProperty(i)) {
          result[i] = deepClone(target[i]);
        }
      }
    }
  } else {
    result = target;
  }
  return result;
}

function resetQuery() {
  initPage()
}

</script>

<style scoped lang="scss">
.header {
  margin-top: 20px;
  margin-left: 20px;
}

.wordSentence{
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column; /* 关键：垂直排列 */
  gap: 10px; /* 项目间距 */
}

</style>
